/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable no-use-before-define */
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable arrow-body-style */
/* eslint-disable import/no-extraneous-dependencies */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import { Form, Input, Button, Select, Row, Col, Popover, Progress, Checkbox, message } from 'antd';
import queryString from 'query-string';
import { password } from '@/components/_utils/rule';
import Captcha from '@/components/Captcha';
import { encryption } from '@/utils/utils';
import styles from './Register.less';
import stylesLogin from './Login.less';

const FormItem = Form.Item;
const { Option } = Select;
const InputGroup = Input.Group;

const passwordStatusMap = {
  ok: <div className={styles.success}>强度：强</div>,
  pass: <div className={styles.warning}>强度：中</div>,
  poor: <div className={styles.error}>强度：太短</div>,
};

const passwordProgressMap = {
  ok: 'success',
  pass: 'normal',
  poor: 'exception',
};

@connect(({ register, loading, setting }) => ({
  register,
  submitting: loading.effects['register/submit'],
  ...setting,
}))
@Form.create()
export default class Register extends PureComponent {
  state = {
    agree: true,
    count: 0,
    confirmDirty: false,
    visible: false,
    help: '',
    prefix: '86',
  };

  componentDidMount() {
    const {
      location: { pathname },
    } = this.props;
    let currentAction;
    if (pathname === '/set/safe') {
      // 安全设置
      currentAction = 'modify';
    } else if (pathname === '/user/forget') {
      // 忘记密码
      currentAction = 'forget';
    } else {
      // 注册
      currentAction = 'register';
    }
    this.setState({
      currentAction,
    });
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  // 获取验证码
  onGetCaptcha = ({ token, site_key }) => {
    return new Promise((resolve, reject) => {
      const { form, dispatch } = this.props;
      const { currentAction } = this.state;
      form.validateFields(['phone'], { force: true }, (err, values) => {
        let value;
        if (!err) {
          this.setState({
            captchaLoading: true,
          });
          if (currentAction == 'register') {
            value = { ...values, type: 'reg' };
          } else if (currentAction == 'modify') {
            value = { ...values, type: 'reset' };
          } else if (currentAction == 'forget') {
            value = { ...values, type: values.phone };
          }
          dispatch({
            type: 'register/getCaptcha',
            payload: {
              ...value,
              token,
              site_key,
            },
          }).then(res => {
            this.setState({
              captchaLoading: false,
            });
            resolve(res);
          });
        } else {
          reject(err);
        }
      });
    });
  };

  getPasswordStatus = () => {
    const { form } = this.props;
    const value = form.getFieldValue('pass');
    if (value && value.length > 9) {
      return 'ok';
    }
    if (value && value.length > 8) {
      return 'pass';
    }
    return 'poor';
  };

  handleSubmit = e => {
    e.preventDefault();
    const { form, dispatch } = this.props;
    const { currentAction, agree } = this.state;
    if (currentAction === 'register' && !agree) {
      message.error('请仔细阅读服务条款，确认同意才可注册');
      return;
    }

    form.validateFields({ force: true }, async (err, values) => {
      const { pass, phone, repass } = values;
      if (!err) {
        const encryptedVal = await encryption({ pass, repass, phone });
        dispatch({
          type: 'register/submit',
          payload: {
            ...values,
            ...encryptedVal,
          },
          currentAction,
          then: () => {
            dispatch(
              routerRedux.push({
                pathname: '/user/login',
                state: {
                  phone,
                },
              }),
            );
          },
        });
      }
    });
  };

  handleConfirmBlur = e => {
    const { value } = e.target;
    const { confirmDirty } = this.state;
    this.setState({ confirmDirty: confirmDirty || !!value });
  };

  checkConfirm = (rule, value, callback) => {
    const { form } = this.props;
    if (value && value !== form.getFieldValue('pass')) {
      callback('两次输入的密码不匹配!');
    } else {
      callback();
    }
  };

  checkPassword = (rule, value, callback) => {
    if (!value) {
      this.setState({
        help: '请输入密码！',
        visible: !!value,
      });
      callback('error');
    } else {
      this.setState({
        help: '',
      });
      const { visible, confirmDirty } = this.state;
      if (!visible) {
        this.setState({
          visible: !!value,
        });
      }
      // const reg = /^(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,15}$/;
      const reg = password.pattern;
      if (value.length < 8 || value.length > 15) {
        callback(value);
        this.setState({
          help: '密码位数不正确！',
        });
      } else if (!reg.test(value)) {
        callback(value);
        this.setState({
          help: '密码格式不正确！',
        });
      } else {
        const { form } = this.props;
        if (value && confirmDirty) {
          form.validateFields(['repass'], { force: true });
        }
        callback();
      }
    }
  };

  changePrefix = value => {
    this.setState({
      prefix: value,
    });
  };

  changeAgree = () => {
    const { agree } = this.state;
    this.setState({
      agree: !agree,
    });
  };

  renderPasswordProgress = () => {
    const { form } = this.props;
    const value = form.getFieldValue('pass');
    const passwordStatus = this.getPasswordStatus();
    return value && value.length ? (
      <div className={styles[`progress-${passwordStatus}`]}>
        <Progress
          status={passwordProgressMap[passwordStatus]}
          className={styles.progress}
          strokeWidth={6}
          percent={value.length * 10 > 100 ? 100 : value.length * 10}
          showInfo={false}
        />
      </div>
    ) : null;
  };

  render() {
    const { form, submitting, location, phone: currentPhones, currentUser, options } = this.props;
    const { loginBg, key, showAdv } = options;
    const currentPhone = currentUser ? currentUser.user_info.phone : currentPhones;
    const { getFieldDecorator } = form;
    const { prefix, help, visible, agree, captchaLoading, currentAction } = this.state;
    const { search } = location;
    const { phone = currentPhone } = queryString.parse(search);
    const isKbCity = key === 'yz' && showAdv; // 仅适配快宝新零售平台登录页样式

    return (
      <div className={styles.main_content}>
        <Row
          style={{ width: '100%', ...(isKbCity ? { margin: 0, height: 632 } : {}) }}
          type="flex"
          justify={isKbCity ? 'space-between' : 'center'}
          gutter={['48', '48']}
          align="middle"
        >
          <Col
            xs={isKbCity ? 0 : 24}
            sm={isKbCity ? 0 : 24}
            md={isKbCity ? 0 : 24}
            lg={isKbCity ? 0 : 24}
            xl={10}
            style={isKbCity ? { padding: 0, flex: 1 } : { width: 500 }}
          >
            <Row type="flex" justify="center">
              <Col style={{ width: isKbCity ? '100%' : 500 }}>
                <div
                  className={styles.main_left}
                  style={{
                    backgroundImage: `url(${loginBg.url})`,
                    height: loginBg.height,
                  }}
                />
              </Col>
            </Row>
          </Col>
          <Col
            xs={24}
            sm={24}
            md={24}
            lg={24}
            xl={10}
            className={isKbCity ? stylesLogin.loginposition : ''}
          >
            <div className={styles.main}>
              <Form
                onSubmit={this.handleSubmit}
                className={currentAction === 'register' ? styles.register_form : ''}
              >
                <FormItem>
                  <InputGroup compact>
                    <Select
                      size="large"
                      value={prefix}
                      onChange={this.changePrefix}
                      style={{ width: '22%' }}
                    >
                      <Option value="86">+86</Option>
                    </Select>
                    {getFieldDecorator('phone', {
                      initialValue: phone,
                      rules: [
                        {
                          required: true,
                          message: '请输入手机号！',
                        },
                        {
                          pattern: /^1\d{10}$/,
                          message: '手机号格式错误！',
                        },
                      ],
                      validateTrigger: 'onBlur',
                    })(
                      <Input
                        size="large"
                        disabled={currentAction === 'modify'}
                        style={{ width: '78%' }}
                        placeholder="11位手机号"
                      />,
                    )}
                  </InputGroup>
                </FormItem>
                <div style={{ height: 0, overflow: 'hidden' }}>
                  <input type="password" name="pass" />
                </div>
                <FormItem>
                  <Row gutter={8}>
                    <Col span={16}>
                      {getFieldDecorator('code', {
                        rules: [
                          {
                            required: true,
                            message: '请输入短信验证码！',
                          },
                          {
                            min: 4,
                            message: '至少输入4位',
                          },
                          {
                            max: 8,
                            message: '最多输入8位',
                          },
                        ],
                      })(<Input size="large" autoComplete="off" placeholder="短信验证码" />)}
                    </Col>
                    <Col span={8}>
                      <Captcha
                        loading={captchaLoading}
                        type="primary"
                        onGetCaptcha={this.onGetCaptcha}
                      >
                        获取验证码
                      </Captcha>
                    </Col>
                  </Row>
                </FormItem>
                <FormItem help={help}>
                  <Popover
                    content={
                      <div style={{ padding: '4px 0' }}>
                        {passwordStatusMap[this.getPasswordStatus()]}
                        {this.renderPasswordProgress()}
                        <div style={{ marginTop: 10 }}>
                          请输入英文字母加数字，且位数为8-15位的密码。
                        </div>
                      </div>
                    }
                    overlayStyle={{ width: 240 }}
                    placement="right"
                    visible={visible}
                  >
                    {getFieldDecorator('pass', {
                      rules: [
                        {
                          validator: this.checkPassword,
                        },
                      ],
                      validateTrigger: 'onBlur',
                    })(<Input size="large" type="password" placeholder="请输入密码" />)}
                  </Popover>
                </FormItem>
                <FormItem>
                  {getFieldDecorator('repass', {
                    rules: [
                      {
                        required: true,
                        message: '请确认密码！',
                      },
                      {
                        validator: this.checkConfirm,
                      },
                    ],
                  })(<Input size="large" type="password" placeholder="确认密码" />)}
                </FormItem>
                {currentAction === 'register' && (
                  <FormItem>
                    <Checkbox checked={agree} onChange={this.changeAgree}>
                      同意并接受
                    </Checkbox>
                    <span className={styles.blue}>《注册服务条款》</span>
                  </FormItem>
                )}
                <FormItem>
                  <Button
                    size="large"
                    loading={submitting}
                    className={styles.submit}
                    type="primary"
                    htmlType="submit"
                    block
                  >
                    {currentAction === 'register' ? '同意注册' : '确认修改'}
                  </Button>
                  {currentAction !== 'modify' && (
                    <Link className={styles.login} to="/user/login">
                      {currentAction === 'register' ? '使用已有账户登录' : '立即登录'}
                    </Link>
                  )}
                </FormItem>
              </Form>
            </div>
          </Col>
        </Row>
      </div>
    );
  }
}
